var MAP = 'selectedConditions', PAGE_LENGTH, PAGE_RETURN;
var category = 0;
var pageAmountList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var pageNumList = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
var preMainBoards = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
var preOthers = '0@0@0@0@0@0@0@0@0@0@0@0@';

function changeList() {
	var minIndex = PAGE_LENGTH*((pageNumList[category]-1)%PAGE_RETURN);
	var maxIndex = minIndex + PAGE_LENGTH;
	$('#choose'+category+' .choose-bd .list-item').each(function(index) {
		if (minIndex<=index && index<maxIndex) {
			$(this).removeClass('hide');
		} else {
			$(this).addClass('hide');
		}
	});
}

function loadPart() {
	parameters = new Object();
	parameters['category'] = category;
	parameters['sortOrder'] = $('#choose'+category+' .choose-bd .middle .sort select').val();
	parameters['pageNum'] = pageNumList[category];
	$('#choose'+category+' .choose-bd .filter select').each(function(index) {
		var value = $(this).val();
		if (value != 0) {
			parameters[MAP+"['"+$(this).attr('name')+"']"] = value;
		}
	});
	/*-----=====浏览器控制台输出=====-----
	for (var v in parameters) {
		console.log(v+': '+parameters[v]);
	}
	-----=========================-----*/
	$.post(BASEPATH+'/diyLoadPart.do', parameters, function(data) {
		var chooseBody = $('#choose'+category+' .choose-bd');
		chooseBody.find('.middle').nextAll().remove();
		chooseBody.append(data);
		changeList();
		initialPageBar(pageAmountList[category], pageNumList[category], chooseBody.find('.page-bar'));
	}, 'html');
}

function turnPage(event) {
	var a = $(event.target);
	var text = a.text();
	if (text != pageNumList[category]) {
		var prePageNum = pageNumList[category];
		//改变页数
		if (text == '<上一页') {
			pageNumList[category]--;
		} else if (text == '下一页>') {
			pageNumList[category]++;
		} else {
			pageNumList[category] = +text;
		}
		//判断翻页前后页数是否在同一个页面缓存窗口（比如10页）
		if (Math.floor((pageNumList[category]-1)/PAGE_RETURN) == Math.floor((prePageNum-1)/PAGE_RETURN)) {
			//直接翻页
			changeList();
			a.siblings().remove();
			a.remove();
			initialPageBar(pageAmountList[category], pageNumList[category], $('#choose'+category+' .choose-bd .page-bar'));
		} else {
			//重新请求列表
			loadPart();
		}
	}
}

function getHardwares() {
    var hardwares = new Object();
    $('.scheme-bd tbody tr').each(function(index) {
        var hardwareId = $(this).attr('name');
        if (hardwareId == '0') {
            hardwares['hardwares['+index+']'] = '0';
        } else {
            var select = $(this).find('.num select');
            var amount = 1;
            if (select.length != 0) {
                amount = select.val();
            }
            hardwares['hardwares['+index+']'] = hardwareId + '@' + amount;
        }
    });
    /*-----=====浏览器控制台输出=====-----
    for (var v in hardwares) {
        console.log(v+': '+hardwares[v]);
    }
    -----=========================-----*/
   return hardwares;
}

function getTips() {
	var totalPrice = 0;
    $('.scheme-bd tbody tr').each(function(index) {
        var hardwareId = $(this).attr('name');
        if (hardwareId != '0') {
        	var price = $(this).find('.price b').text().replace(',', '');
            var select = $(this).find('.num select');
            var amount = 1;
            if (select.length != 0) {
                amount = select.val();
            }
            totalPrice += price * amount;
        }
    });
	$('.scheme-bd tfoot tr .total b').text(totalPrice);
	$.post(BASEPATH+'/diyGetTips.do', getHardwares(), function(data) {
		$(data).replaceAll($('.tips'));
	}, 'html');
}

function addHardware(event) {
	var a = $(event.target);
	if (!a.hasClass('selected')) {
		//将选中项加入配置单中
		$('#choose'+category+' .choose-bd .list-item .select.selected').removeClass('selected');
    	a.addClass('selected');
    	var tr = $('#'+category);
    	var paramDiv = a.prev();
    	tr.attr('name', paramDiv.children('.id').val());
    	tr.find('.model span').html(paramDiv.children('h3').html());
    	if (category==2 || category==3) {
    		tr.children('.num').html('\
    			<select onchange="modifyNum();">\
					<option value="1" selected="selected">1</option>\
					<option value="2">2</option>\
					<option value="3">3</option>\
					<option value="4">4</option>\
				</select>');
    	} else {
    		tr.children('.num').html('1');
    	}
    	tr.children('.price').html('&yen;<b>'+paramDiv.find('li:nth-child(1) b').text()+'</b>');
    	tr.children('.cancel').html('<a href="javascript:void(0);" onclick="removeHardware(event);" class="blue">取消</a>');
    	//获取提示信息
    	getTips();
	}
}

function removeHardware(event) {
	//在配置单中将取消的项移除
	var a = $(event.target);
	var tr = a.parents('tr');
	tr.attr('name', '0');
	tr.find('.model span').html('');
	tr.children('.num').html('');
	tr.children('.price').html('');
	tr.children('.cancel').html('');
	$('#choose'+tr.attr('id')+' .choose-bd .list-item .select.selected').removeClass('selected');
	//获取提示信息
    getTips();
}

function modifyNum() {
	getTips();
}

function verify() {
	var ok = true;
    $('.scheme-bd tbody tr').slice(0,4).each(function(index) {
        if ($(this).attr('name') == '0') {
        	var text = $(this).children('.part').text();
			alert('请选择' + text.substring(0, text.length-1) + '！');
			ok = false;
			return false;
        }
    });
    if (ok == false) {
    	return ok;
    }
	$('.scheme-bd form li span').each(function(index) {
		if ($(this).next().val() == '') {
        	var text = $(this).text();
			alert('请填写' + text.substring(0, text.length-1) + '！');
			ok = false;
			return false;
        }
    });
    return ok;
}

function submitScheme() {
	if (verify()) {
		var scheme = getHardwares();
		var inputList = [$('#schemeType'), $('#schemeTitle'), $('#schemeDescription')];
		for (var i in inputList) {
            var input = inputList[i];
            scheme[input.attr('name')] = input.val();
        }
		$.post(BASEPATH+'/addScheme.do', scheme, function(data) {
			window.location.href = BASEPATH + '/user/userScheme.do';
		}, 'text');
	}
}

$(document).ready(function() {
	//初始化页面
	$('#0').addClass('selected');
	$('#choose0').removeClass('hide');
	$('.choose-bd select option:nth-child(1)').attr('selected', 'selected');
	changeList();
	initialPageBar(pageAmountList[0], pageNumList[0], $('#choose0 .choose-bd .page-bar'));
	
	//事件监听
    $('.scheme-bd tbody tr').click(function() {
    	//改变配置单中选中行
    	$('.scheme-bd tbody tr.selected').removeClass('selected');
    	$(this).addClass('selected');
    	//移动中间三角形
    	var rowNum = $(this).attr('id');
    	var triangle = $('.scheme .triangle');
    	triangle.css('top', 40+37*rowNum+'px');
    	//选择不同行,则切换右边筛选列表
    	if (category != rowNum) {
    		category = +rowNum;
	    	$('.choose').addClass('hide');
	    	$('#choose'+rowNum).removeClass('hide');
	    	if (category == 0) {
	    		//如果点选主板时其它硬件与上次选择时发生了变化，则重新请求列表
	    		var nowOthers = '';
	    		for (var i=1; i<13; i++) {
	    			nowOthers = nowOthers + $('#'+i).attr('name') + '@';
	    		}
	    		if (nowOthers != preOthers) {
	    			//更新preOthers
					preOthers = nowOthers;
					//重新请求列表
					pageNumList[category] = 1;
			    	loadPart();
	    		}
	    	} else {
		    	//如果列表从未加载过，
		    	//或当前主板与上次硬件选择时主板不同，
		    	//则重新请求列表
		    	if ($('#choose'+rowNum+' .choose-bd .middle').next().length==0 || $('#0').attr('name')!=preMainBoards[category]) {
					//更新preMainBoards
					preMainBoards[category] = $('#0').attr('name');
					//重新请求列表
					pageNumList[category] = 1;
			    	loadPart();
	    		}
	    	}
    	}
	});
	$('.choose-bd select').change(function() {
		//重新请求列表
		pageNumList[category] = 1;
		loadPart();
	});
});